package com.zyl.blog.tasks.schedule.container;

import com.zyl.blog.tasks.schedule.abstracts.AbstractScheduledTask;
import jakarta.annotation.Resource;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;
import java.util.stream.Collectors;

/**
 * 用户任务容器实现类，使用ConcurrentHashMap保证线程安全
 * @version v1.0
 * @ProjectName: Personal_Blog_Server
 * @Package: com.zyl.blog.tasks.schedule.container
 * @ClassName: UserTaskContainer
 * @Author FinalFantasy
 * @Date 2025/8/12-10:18
 */
@Component
public class UserTaskContainer implements TaskContainer {

    /* 存储所有任务：Map<用户名, Map<任务名, 任务对象>> */
    private final Map<String, Map<String, AbstractScheduledTask>> userTasks = new ConcurrentHashMap<>();

    /* 存储正在运行的任务：Map<用户名, Map<任务名, ScheduledTask>> */
    private final Map<String, Map<String, ScheduledFuture<?>>> runningTasks = new ConcurrentHashMap<>();

    @Resource
    private TaskScheduler taskScheduler;

    /**
     * 实现接口方法，返回注入的TaskScheduler实例
     */
    @Override
    public TaskScheduler getTaskScheduler() {
        return taskScheduler;
    }

    /**
     * 添加用户的任务
     * @param task  任务对象
     */
    @Override
    public void addTask(AbstractScheduledTask task) {
        String username = task.getUsername();
        String taskName = task.getTaskName();

        /* 确保用户的任务Map存在 */
        userTasks.computeIfAbsent(username, _ -> new ConcurrentHashMap<>());

        /* 存储任务 */
        userTasks.get(username).put(taskName, task);
    }

    /**
     * 移除用户的指定任务
     * @param taskName  任务名
     * @param username  用户名
     */
    @Override
    public void removeTask(String taskName, String username) {
        Map<String, AbstractScheduledTask> tasks = userTasks.get(username);
        if (tasks != null) {
            tasks.remove(taskName);

            /* 如果用户没有任务了，移除用户 */
            if (tasks.isEmpty()) {
                userTasks.remove(username);
            }
        }
    }

    /**
     * 获取用户的指定任务
     * @param taskName  任务名
     * @param username  用户名
     * @return {@link AbstractScheduledTask }
     */
    @Override
    public AbstractScheduledTask getTask(String taskName, String username) {
        Map<String, AbstractScheduledTask> tasks = userTasks.get(username);
        return tasks != null ? tasks.get(taskName) : null;
    }

    /**
     * 获取用户的所有任务
     * @param username  用户名
     * @return {@link List }<{@link AbstractScheduledTask }>
     */
    @Override
    public List<AbstractScheduledTask> getUserTasks(String username) {
        Map<String, AbstractScheduledTask> tasks = userTasks.get(username);
        return tasks != null ? new ArrayList<>(tasks.values()) : Collections.emptyList();
    }

    /**
     * 获取所有任务
     * @return {@link Map }<{@link String }, {@link Map }<{@link String }, {@link AbstractScheduledTask }>>
     */
    @Override
    public Map<String, Map<String, AbstractScheduledTask>> getAllTasks() {
        return new HashMap<>(userTasks);
    }

    /**
     * 存储正在运行的任务
     */
    @Override
    public void storeRunningTask(String taskName, String username, ScheduledFuture<?> scheduledFuture) {
        runningTasks.computeIfAbsent(username, _ -> new ConcurrentHashMap<>())
                .put(taskName, scheduledFuture);
    }

    /**
     * 获取正在运行的任务
     */
    @Override
    public ScheduledFuture<?> getRunningTask(String taskName, String username) {
        Map<String, ScheduledFuture<?>> tasks = runningTasks.get(username);
        return tasks != null ? tasks.get(taskName) : null;
    }

    /**
     * 移除正在运行的任务
     */
    @Override
    public void removeRunningTask(String taskName, String username) {
        Map<String, ScheduledFuture<?>> tasks = runningTasks.get(username);
        if (tasks != null) {
            tasks.remove(taskName);
            if (tasks.isEmpty()) {
                runningTasks.remove(username);
            }
        }
    }

    /**
     * 获取调度的任务
     */
    @Override
    public ScheduledFuture<?> getScheduledTask(String taskName, String username) {
        return getRunningTask(taskName, username);
    }

    /**
     * 移除调度的任务
     */
    @Override
    public void removeScheduledTask(String taskName, String username) {
        removeRunningTask(taskName, username);
    }

    /**
     * 添加调度的任务
     */
    @Override
    public void addScheduledTask(String taskName, String username, ScheduledFuture<?> scheduledFuture) {
        storeRunningTask(taskName, username, scheduledFuture);
    }

    /**
     * 检查任务是否正在运行
     */
    @Override
    public boolean isTaskRunning(String taskName, String username) {
        ScheduledFuture<?> future = getRunningTask(taskName, username);
        return future != null && !future.isCancelled() && !future.isDone();
    }

    /**
     * 获取用户所有正在运行的任务
     */
    @Override
    public List<AbstractScheduledTask> getUserRunningTasks(String username) {
        Map<String, ScheduledFuture<?>> running = runningTasks.get(username);
        if (running == null || running.isEmpty()) {
            return Collections.emptyList();
        }

        Map<String, AbstractScheduledTask> allUserTasks = userTasks.get(username);
        if (allUserTasks == null) {
            return Collections.emptyList();
        }

        // 找出所有正在运行且存在于用户任务中的任务
        return running.keySet().stream()
                .filter(allUserTasks::containsKey)
                .map(allUserTasks::get)
                .collect(Collectors.toList());
    }
}
